<template>
  <PageWrapper v-loading="loginLoading" loading-tip="登录中...">
    <BasicTable
      @register="registerTable"
      :rowSelection="
        checkboxShow
          ? {
              type: 'checkbox',
              columnWidth: 44,
              selectedRowKeys: checkedDelKeys,
              onChange: onSelectChange,
              getCheckboxProps: onGetCheckboxProps
            }
          : null
      "
    >
      <template #form-channelCode="{ model, field }">
        <a-tree-select
          v-model:value="model[field]"
          :tree-data="channelTreeData"
          @change="treeSelectChange(model[field])"
          multiple
          allowClear
          :field-names="{
            label: 'channelName',
            value: 'channelCode',
            children: 'children'
          }"
          treeNodeFilterProp="channelName"
          placeholder="请选择渠道名称"
          :maxTagCount="3"
          showCheckedStrategy="SHOW_ALL"
        ></a-tree-select>
      </template>
      <template #tableTitle>
        <a-space :size="12">
          <a-button
            type="primary"
            v-auth="permissionCodeMap.tenantAdd"
            @click="openOrganization(operateActionTypeMap.ADD)"
            >新增租户</a-button
          >
          <a-button type="primary" ghost v-auth="permissionCodeMap.tenantBatchAdd" @click="openPatchOrganization"
            >批量新增</a-button
          >
          <a-button :disabled="!checkedDelKeys.length" v-auth="permissionCodeMap.tenantDel" @click="batchDel"
            >删除租户</a-button
          >
        </a-space>
      </template>

      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'endTimeRemainingDays'">
          <div class="last-time">
            <span class="time-num" v-if="record.endTimeRemainingDays || record.endTimeRemainingDays == 0">
              {{ record.endTimeRemainingDays }}
            </span>
            <span>{{ record.endTimeRemainingDays || record.endTimeRemainingDays === 0 ? '天' : '永久' }}</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'taxesAuthFlag'">
          <span class="global-stop-status" v-if="record.taxesAuthFlag == 0"> 未认证 </span>
          <span class="global-active-status" v-else-if="record.taxesAuthFlag == 1"> 已认证 </span>
        </template>
        <template v-else-if="column.dataIndex === 'orgStatus'">
          <span class="global-active-status" v-if="record.orgStatus == 0"> 启用 </span>
          <span class="global-stop-status" v-else-if="record.orgStatus == 1"> 停用 </span>
        </template>
        <template v-else-if="column.dataIndex === 'tenantIdCount'">
          <span :class="record.tenantIdCount ? 'global-primary-text' : 'global-disabled-text'" @click="viewNum(record)">
            {{ record.tenantIdCount || 0 }}个
          </span>
        </template>
        <template v-else-if="column.dataIndex === 'operate'">
          <a-button
            type="link"
            v-auth="permissionCodeMap.tenantView"
            class="g-operate-btn"
            @click="openOrganization(operateActionTypeMap.VIEW, record.tenantId, record)"
            >查看</a-button
          >
          <a-button
            type="link"
            class="g-operate-btn"
            v-auth="permissionCodeMap.tenantEdit"
            @click="openOrganization(operateActionTypeMap.EDIT, record.tenantId, record)"
            >编辑</a-button
          >
          <a-button
            type="link"
            v-auth="permissionCodeMap.tenantLogin"
            class="g-operate-btn"
            @click="jumpLogin(record.tenantId)"
            >登录</a-button
          >
          <!-- <a-button
            type="link"
            class="g-operate-btn"
            v-auth="permissionCodeMap.tenantAuth"
            @click="openOrganizationAuth(record)"
            >授权</a-button
          > -->
        </template>
      </template>
    </BasicTable>
    <TenantAdd @register="tenantAddRegister" @operateSuccess="operateSuccess" @resetPwd="resetPwd" />
    <TenantBatchAdd @register="tenantBatchAddRegister" @operateSuccess="operateSuccess" />
    <TenantDel @register="tenantDelRegister" @operateSuccess="operateSuccess" />
    <TenantNum @register="tenantNumRegister" />
    <!-- <TenantAuth
      @register="tenantAuthRegister"
      @backEdit="openOrganization(operateActionTypeMap.EDIT, currentTenantId)"
    /> -->
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, nextTick, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getTenantBasicColumns, getSearchFormConfig, getRegChannelMap } from './dataSource'
import { useDrawer } from '@/components/Drawer'
import { useModal } from '@/components/Modal'
import TenantAdd from './components/TenantAdd.vue'
import TenantBatchAdd from './components/TenantBatchAdd.vue'
import TenantAuth from './components/TenantAuth.vue'
import TenantDel from './components/TenantDel.vue'
import TenantNum from './components/TenantNum.vue'
import { userStore } from '@/store/modules/user'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { operateActionType, operateTxtType, constantMap } from '@/types/enum'
import { TenantRecord } from '@/types/tenant'
import { message } from 'ant-design-vue'
import api from '@/api'
import type { RouteLocationNormalizedLoaded, LocationQuery } from 'vue-router'
import { useRouter } from 'vue-router'
import { transformToTree, createChannelTree } from '@/utils'

const { currentRoute } = useRouter()

const { enterpriseList, enterpriseAuthLogin, queryChannelList } = api
const userModule = userStore()

const operateActionTypeMap = operateActionType
const currentTenantId = ref('')
const loginLoading = ref(false)

const checkedDelKeys = ref<Array<string | number>>([])
const checkedDelList = ref<Array<TenantRecord>>([])
const checkboxShow = computed(() => userModule.permissionActionList.includes(permissionCodeMap.tenantDel))

const channelTreeData = ref<any>([])
const seclectedChannel = ref<any>([])
onMounted(async () => {
  const res = await queryChannelList()
  channelTreeData.value = transformToTree(res.result)
  console.log(res.result, channelTreeData.value)
})
const treeSelectChange = (data: any) => {
  console.log('测试数据======>', data)
  seclectedChannel.value = data
}

const [registerTable, { reload, setPagination, getForm }] = useTable({
  api: enterpriseList,
  columns: getTenantBasicColumns(),
  afterFetch: afterDataFetch,
  beforeFetch: beforeParamsFetch,
  useSearchForm: true,
  showIndexColumn: true,
  indexColumnProps: {
    fixed: 'left'
  },
  formConfig: getSearchFormConfig(),
  rowKey: 'tenantId',
  scroll: { y: constantMap.tableYHeight, x: constantMap.tableXWidth }
})

function beforeParamsFetch(params: any) {
  const { channelCode, ...rest } = params
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  const formChannel = formData.channelCode
  let channelCodeSet
  if (seclectedChannel.value.length > 0 && formChannel) {
    channelCodeSet = seclectedChannel.value
  }
  let paramsData = {
    ...rest,
    channelCodeSet
  }
  return paramsData
}

// 表格返回数据处理
function afterDataFetch(data: TenantRecord[]) {
  let channelMap = getRegChannelMap()
  data.forEach((item) => {
    item.regChannelValue = item.regChannel || item.regChannel === 0 ? channelMap[item.regChannel] : ''
  })
  return data
}

const [tenantAddRegister, { openDrawer: OrganizationAddOpenDrawer, setDrawerProps }] = useDrawer()
const [tenantBatchAddRegister, { openDrawer: OrganizationPatchAddOpenDrawer }] = useDrawer()
// const [tenantAuthRegister, { openDrawer: OrganizationAuthOpenDrawer }] = useDrawer()
const [tenantDelRegister, { openModal: tenantDelOpenModal }] = useModal()
const [tenantNumRegister, { openModal: tanantNumModal }] = useModal()

const openOrganization = (type: OperateType, tenantId?: string, record?: TenantRecord) => {
  setDrawerProps({
    title: operateTxtType[type],
    showOkBtn: type === operateActionTypeMap.VIEW ? false : true,
    cancelText: type === operateActionTypeMap.VIEW ? '关闭' : '取消'
  })
  currentTenantId.value = tenantId || ''
  OrganizationAddOpenDrawer(true, {
    type,
    record,
    tenantId
  })
}
const openPatchOrganization = () => {
  OrganizationPatchAddOpenDrawer(true, {})
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    if (route.params && route.params.type === 'add') {
      nextTick(() => {
        setTimeout(() => {
          openOrganization(operateActionTypeMap.ADD)
        }, 1000)
      })
    }
  },
  {
    immediate: true
  }
)

const onSelectChange = (selectedRowKeys: (string | number)[], selectedRow: TenantRecord[]) => {
  checkedDelKeys.value = selectedRowKeys
  checkedDelList.value = selectedRow
}
// 禁用
const onGetCheckboxProps = (record: TenantRecord) => {
  return {
    disabled: record.orgStatus !== 1
  }
}
// 登录
const jumpLogin = async (tenantId: string) => {
  try {
    loginLoading.value = true
    let res = await enterpriseAuthLogin({
      entTenantId: tenantId
    })
    let token = res.result
    if (token) {
      window.open(import.meta.env.VITE_JUMP_LOGIN + '?accessToken=' + token, '_blank')
    } else {
      message.error('登录失败')
    }
    loginLoading.value = false
  } catch (error) {
    loginLoading.value = false
  }
}
// 授权
// const openOrganizationAuth = (record: TenantRecord) => {
//   if (record.orgStatus === 1) {
//     return message.error('该企业已停用')
//   }
//   currentTenantId.value = record.tenantId
//   OrganizationAuthOpenDrawer(true, {
//     record
//   })
// }
// 删除
const batchDel = () => {
  tenantDelOpenModal(true, {
    checkedDelKeys: checkedDelKeys.value,
    checkedDelList: checkedDelList.value
  })
}
// 查看数量
const viewNum = (record: TenantRecord) => {
  if (record.tenantIdCount) {
    tanantNumModal(true, {
      record
    })
  }
}
const resetPwd = () => {
  tenantDelOpenModal(true, {
    type: 'resetPwd',
    tenantId: currentTenantId.value
  })
}
const operateSuccess = () => {
  setPagination({
    current: 1
  })
  reload()
}
</script>

<style lang="less" scoped>
:deep(.ant-table-wrapper) {
  overflow-x: hidden;
}
.time-num {
  color: @primary-color;
}
</style>
